<script setup>
import router from "@/router/index.js";
import { ref, onMounted } from "vue";
import {queryTeamDetail, userJoinTeam} from "@/api/team.js";
import {showToast} from "vant";

const active = ref(0);
const countdown = ref('');
const onClickLeft = () => router.back();
const teamPassword = ref('');
const pwDialogShow = ref(false);
const id = ref();

const teamInfo = ref({
  id: 0,
  teamNumber: '',
  teamName: '',
  userId: 0,
  nickname: '',
  image: '',
  tags: [],
  maxMember: 0,
  memberNum: 0,
  teamDesc: '',
  type: 0,
  isLimit: 0,
  beginTime: '',
  endTime: '',
  isMember: 0,
  isOwner: 0
});

/**
 * 获取当前队伍信息
 */
const getTeamInfo = () => {
  // 获取路由中的队伍id
  const params = router.currentRoute.value.params
  id.value = params.id
  // 获取队伍信息
  queryTeamDetail(id.value).then(res => {
    if (res.data.code === 1){
      teamInfo.value = res.data.data
    } else {
      showToast('获取队伍信息失败')
    }
  }).catch(error => {
    console.log(error)
  })
}
getTeamInfo()

const updateCountdown = () => {
  const now = new Date();
  const begin = new Date(teamInfo.value.beginTime);
  const end = new Date(teamInfo.value.endTime);

  if (now < begin) {
    const diff = Math.floor((begin - now) / 1000);
    const hours = Math.floor(diff / 3600);
    const minutes = Math.floor((diff % 3600) / 60);
    const seconds = diff % 60;
    countdown.value = `${hours}小时${minutes}分钟${seconds}秒后可加入`;
  } else if (now >= begin && now < end) {
    countdown.value = '加入队伍';
  } else {
    countdown.value = '加入已过期';
  }
};

/**
 * 限时加入队伍
 */
const onClickTimedJoinBtn = () => {
  // 判断是否到达加入时间
  const now = new Date();
  const begin = new Date(teamInfo.value.beginTime);
  const end = new Date(teamInfo.value.endTime);
  if (now < begin) {
    showToast('加入时间未到')
  }else if (now >= end) {
    showToast('加入已过期')
  }
  if (teamInfo.value.type === 1){
    pwDialogShow.value = true
  }
  if(teamPassword.value !== '' || teamInfo.value.type !==1){
    const dataForm = {
      id: teamInfo.value.id,
      teamPassword: teamPassword.value
    }
    userJoinTeam(dataForm).then(res => {
      if (res.data.code === 1) {
        console.log(res)
      }else {
        showToast(res.data.msg)
      }
    }).catch(error => {
      console.log(error)
    })
  }
}

/**
 * 非限时
 */
const onClickPrimaryJoinBtn = () => {
  if (teamInfo.value.type === 1){
    pwDialogShow.value = true
  }
  if(teamPassword.value !== '' || teamInfo.value.type !==1){
    const dataForm = {
      id: teamInfo.value.id,
      teamPassword: teamPassword.value
    }
    userJoinTeam(dataForm).then(res => {
      if (res.data.code === 1) {
        console.log(res)
      }else {
        showToast(res.data.msg)
      }
    }).catch(error => {
      console.log(error)
    })
  }
}

const onConfirm = () => {
  // 校验队伍密码：4-16位，必须包含字母和数字
  const passwordRegex = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{4,16}$/;
  if (!passwordRegex.test(teamPassword.value)) {
    showToast('队伍密码必须是4-16位，且包含字母和数字,请重新输入');
    teamPassword.value = ''
    return false;
  }
}

const onCancel = () => {
  teamPassword.value = ''
}

const beforeClose = () => {
  return false
}

onMounted(() => {
  updateCountdown();
  const interval = setInterval(() => {
    updateCountdown();
  }, 1000);

  // Clean up the interval on component unmount
  return () => clearInterval(interval);
});
</script>

<template>
  <div class="team-detail-page">
    <van-nav-bar
      :title="teamInfo.teamName"
      fixed
      left-arrow
      left-text="返回"
      placeholder
      @click-left="onClickLeft"
    >
      <template #right>
        <van-icon v-if="teamInfo.isOwner" name="setting-o">管理</van-icon>
        <van-icon v-else name="setting-o">设置</van-icon>
      </template>
    </van-nav-bar>
    <div class="container">
      <div class="team-detail-content">
        <div class="image">
          <van-image
            :src="teamInfo.image"
            height="110"
            radius="5"
            width="110"
          />
        </div>
        <div class="info">
          <div class="title">
            <div class="leader">队长: {{ teamInfo.nickname }}</div>
            <div class="member">成员: {{ teamInfo.memberNum }}/{{ teamInfo.maxMember }}</div>
          </div>
          <div class="desc"> {{ teamInfo.teamDesc || '队长很懒，暂无简介~' }}</div>
        </div>
      </div>
      <div class="team-tag">
        <div class="tag">
          <van-tag v-for="(item,index) in teamInfo.tags" :key="index" class="tag-item" size="medium" type="primary">
            {{ item }}
          </van-tag>
        </div>
      </div>
      <div v-if="!teamInfo.isMember" class="team-btn-container">
        <div v-if="teamInfo.isLimit" class="team-btn-limit" @click="onClickTimedJoinBtn">
          {{ countdown }}
        </div>
        <div v-else class="team-btn-primary" @click="onClickPrimaryJoinBtn">
          加入队伍
        </div>
      </div>
      <div class="team-num">队伍号：{{teamInfo.teamNumber}}</div>
    </div>
    <van-tabs v-if="teamInfo.isMember" v-model:active="active" animated>
      <van-tab :title="'成员 '+teamInfo.memberNum+'/'+teamInfo.maxMember">成员</van-tab>
      <van-tab title="公告">公告</van-tab>
      <van-tab title="详情">详情</van-tab>
      <van-tab title="聊天"><van-empty description="该功能正在努力开发中，敬请期待~" /></van-tab>
    </van-tabs>
    <van-dialog v-model:show="pwDialogShow" show-cancel-button title="加密队伍" @beforeClose="beforeClose" @cancel="onCancel" @confirm="onConfirm">
      <van-cell-group inset>
        <van-field v-model="teamPassword" label="密码" placeholder="请输入队伍密码" type="password" />
      </van-cell-group>
    </van-dialog>
  </div>
</template>

<style scoped>
.team-detail-page {
  background-color: #f1f1f1;
  min-height: 100vh;
}

.container {
  padding: 10px;
}

.team-detail-content {
  display: flex;
  padding: 10px;
  background-color: #fff;
  border-radius: 5px;
}

.team-detail-content .info .title {
  display: flex;
}

.team-detail-content .info .title .leader, .team-detail-content .info .title .member {
  margin-left: 10px;
  font-size: 13px;
  color: #353639;
}

.team-detail-content .info .desc {
  margin-top: 5px;
  margin-left: 10px;
  font-size: 11px;
  color: #353639;
}

.team-tag {
  padding: 10px;
  margin-top: 10px;
  background-color: #fff;
  border-radius: 5px;
}

.tag {
  display: flex;
  flex-wrap: wrap;
}

.tag .van-tag {
  margin-right: 5px;
  margin-top: 5px;
}

.team-btn-container {
  margin-top: 10px;
}

.team-btn-primary {
  width: 100%;
  height: 42px;
  background: linear-gradient(90deg, #3cd7ec, #1125ff);
  color: #fff;
  border-radius: 39px;
  box-shadow: 0 10px 20px 0 rgba(0, 0, 0, .1);
  letter-spacing: 2px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.team-btn-primary:active {
  background: linear-gradient(90deg, #3cd7ec, rgba(17, 37, 255, 0.76));
}

.team-btn-limit {
  width: 100%;
  height: 42px;
  background: linear-gradient(90deg, #3cecbd, #2111ff);
  color: #fff;
  border-radius: 39px;
  box-shadow: 0 10px 20px 0 rgba(0, 0, 0, .1);
  letter-spacing: 2px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.team-btn-limit:active {
  background-color: #f1f1f1;
}

.team-num {
  margin-top: 10px;
  text-align: center;
  font-size: 12px;
  color: #2f2f32;
}
</style>
